package com.micro.ai.template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.template.entity.TemplateReview;
import com.micro.ai.template.mapper.TemplateReviewMapper;
import com.micro.ai.template.service.TemplateReviewService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 模板审核Service实现
 *
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TemplateReviewServiceImpl extends ServiceImpl<TemplateReviewMapper, TemplateReview>
        implements TemplateReviewService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TemplateReview submitReview(String templateId, String submitterId) {
        log.info("提交审核, templateId: {}, submitterId: {}", templateId, submitterId);

        // 检查是否已有待审核记录
        LambdaQueryWrapper<TemplateReview> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateReview::getTemplateId, templateId)
                .eq(TemplateReview::getStatus, "pending");
        
        if (this.count(wrapper) > 0) {
            throw new BusinessException("该模板已有待审核记录");
        }
        
        // 检查是否已存在待审核记录
        wrapper.clear();
        wrapper.eq(TemplateReview::getTemplateId, templateId)
                .eq(TemplateReview::getStatus, "PENDING");
        
        if (this.count(wrapper) > 0) {
            throw new BusinessException("该模板已有待审核记录");
        }

        TemplateReview review = new TemplateReview();
        review.setTemplateId(templateId);
        review.setReviewerId(submitterId); // 暂时用submitterId作为reviewerId
        review.setStatus("PENDING");
        
        this.save(review);
        log.info("审核提交成功, reviewId: {}", review.getId());
        
        return review;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void approveReview(String reviewId, String reviewerId, String comment) {
        log.info("审核通过, reviewId: {}, reviewerId: {}", reviewId, reviewerId);

        TemplateReview review = this.getById(reviewId);
        if (review == null) {
            throw new BusinessException("审核记录不存在");
        }

        if (!"PENDING".equals(review.getStatus())) {
            throw new BusinessException("该审核已处理");
        }

        review.setStatus("APPROVED");
        review.setReviewerId(reviewerId);
        review.setComment(comment);
        review.setReviewedAt(LocalDateTime.now());
        
        this.updateById(review);
        log.info("审核通过完成");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rejectReview(String reviewId, String reviewerId, String comment) {
        log.info("审核拒绝, reviewId: {}, reviewerId: {}", reviewId, reviewerId);

        TemplateReview review = this.getById(reviewId);
        if (review == null) {
            throw new BusinessException("审核记录不存在");
        }

        if (!"PENDING".equals(review.getStatus())) {
            throw new BusinessException("该审核已处理");
        }

        review.setStatus("REJECTED");
        review.setReviewerId(reviewerId);
        review.setComment(comment);
        review.setReviewedAt(LocalDateTime.now());
        
        this.updateById(review);
        log.info("审核拒绝完成");
    }

    @Override
    public IPage<TemplateReview> getPendingReviews(Page<TemplateReview> page) {
        LambdaQueryWrapper<TemplateReview> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateReview::getStatus, "PENDING")
                .orderByAsc(TemplateReview::getReviewedAt);
        
        return this.page(page, wrapper);
    }

    @Override
    public List<TemplateReview> getTemplateReviewHistory(String templateId) {
        LambdaQueryWrapper<TemplateReview> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateReview::getTemplateId, templateId)
                .orderByDesc(TemplateReview::getReviewedAt);
        
        return this.list(wrapper);
    }

    @Override
    public TemplateReview getCurrentReview(String templateId) {
        LambdaQueryWrapper<TemplateReview> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateReview::getTemplateId, templateId)
                .eq(TemplateReview::getStatus, "PENDING")
                .orderByDesc(TemplateReview::getReviewedAt)
                .last("LIMIT 1");
        
        return this.getOne(wrapper);
    }
}

